
from whiff import resolver
from whiff import whiffenv
from whiff.middleware import misc
from whiff import gateway

def doSearch(env, start_response):
    env = resolver.process_cgi(env, parse_cgi=True)
    resourcePathList = ["search"]
    session = gateway.getResource(env, resourcePathList)
    query = whiffenv.cgiGet(env, "query", "penguin ~bacter")
    pagestr = whiffenv.cgiGet(env, "page", "0").strip()
    page = int(pagestr)
    result = session.result(query)
    idList = result.identities()
    start_response("200 OK", [('Content-Type', "text/html")])
    nrows = 10
    ncolumns = 3
    startindex = page * (nrows*ncolumns)
    yield "<table border><tr>\n"
    if page>0:
        yield '<td> <a href="javascript:changeSearch(-1)"> &lt;&lt; </a> </td>\n'
    index = startindex
    #assert index>=0, "negative start index "+repr(index)
    #assert index<len(idList), "start index is past last query result "+repr((startindex, len(idList)))
    if index<0 or index>len(idList):
        index = 0
    for ncolumn in xrange(ncolumns):
        yield "<td>"
        for rownum in xrange(nrows):
            if index<len(idList):
                thisId = idList[index]
                entry = session.describe(thisId)
                #D = entry.asDictionary()
                #name = D["name_txt"]
                L = entry.getValues("name_txt")
                name = L[0]
                link = "javascript:setFocus('%s')" % thisId
                anchor = '<a href="%s">%s</a>' % (link,name)
                yield anchor
                yield "<br>\n"
            index += 1
        yield "</td>"
    if index<len(idList):
        yield '<td> <a href="javascript:changeSearch(1)"> &gt;&gt; </a> </td>\n'
    yield "</tr></table>\n"

__wsgi__ = doSearch
